<?php

namespace app\admin\controller\businessmanage;

use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use think\exception\DbException;
use think\exception\PDOException;
use Exception;
use fast\Random;
use fast\Tree;
use think\Db;
use think\Validate;

/**
 * 添加推送会员
 */
class Select extends Backend
{

    /**
     * @var \app\admin\model\push_users
     */
    protected $model = null;
    protected $selectpageFields = 'username,nickname';
    protected $searchFields = 'username,nickname,mobile';
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\businessmanage\PushUsers;

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds($this->auth->isSuperAdmin());
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }

        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $bid = $this->request->param('bid');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
            ->with(['admindate'])//关联的表
            ->where('business_id',$bid)
            ->where('is_admin','0')
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        } 
        $this->assign('bid',$this->request->param('ids'));
        $this->assignconfig('bid',$this->request->param('ids'));
        return $this->view->fetch();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        $bid = $this->request->get("bid");
        if (empty($ids)||empty($bid)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        Db::startTrans();
        try {
            $res = $this->model->where(['id'=>$ids])->find();
            $res->delete();
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }
    /**
     * 推送用户列表
     *
     * @return string|Json
     * @throws \think\Exception
     */
    public function pushUser()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $bid = $this->request->get('bid');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = Db::name('admin')
                ->where('id','NOT IN',function($query) use($bid){
                $query->name('push_users')
                    ->where('business_id',$bid)
                    ->where('deletetime','null')
                    ->field('user_id');
                }) 
                ->where('is_admin','0')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        } 
        $this->assign('bid',$this->request->param('bid'));
        $this->assignconfig('bid',$this->request->param('bid'));
        return $this->view->fetch();
    }
    /**
     * 添加推送
     *
     * @param $ids
     * @return void
     */
    public function addPush($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if(!is_array($ids)){
            $ids = explode(',',$ids);
        }
        $bid = $this->request->param('bid');
        Db::startTrans();
        try {
            foreach ($ids as $item) {
                $this->model->create(['user_id'=>$item,'business_id'=>$bid]);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }


    /**
     * 下拉搜索
     */
    public function selectpage()
    {
        $this->dataLimit = 'auth';
        $this->dataLimitField = 'id';
        return parent::selectpage();
    }
}
